/**
 * chenuu.com
 * 
 * @author  zhaoxu.com@gmail.com
 * @created 2012-11-14
 */
package com.chenuu.integration.dropbox.requester;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.InputStreamEntity;

import com.chenuu.integration.dropbox.session.DropboxSession;
import com.chenuu.integration.httpclient.utils.RequestUtil;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.exception.DropboxIOException;

/**
 *
 */
public class DropboxUploader extends DropboxRequester {

	public DropboxUploader(DropboxSession session) {
		super(session);
	}

	/*
	 * (non-Javadoc)
	 * @see com.chenuu.integration.dropbox.requester.DropboxRequester#buildRequest(com.chenuu.integration.dropbox.requester.RequestInfo)
	 */
	@Override
	protected HttpUriRequest buildRequest(RequestInfo requestInfo) throws DropboxException {
		
		UploadInfo uploadInfo = (UploadInfo) requestInfo;

		// --- Step 1: Build URI
		String target = RequestUtil.buildURI(requestInfo.getUri(), requestInfo.getParams());

		HttpPut request = new HttpPut(target);

		File file = new File(uploadInfo.getLocalPath());
		InputStream is = null;
		try {
			is = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			throw new DropboxIOException(e);
		}

		InputStreamEntity entity = new InputStreamEntity(is, file.length());
		entity.setContentEncoding("application/octet-stream");
		entity.setChunked(false);

		request.setEntity(entity);

		return request;
	}

}
